package com.atguigu.day26.day27morning.dbutils07;

import com.atguigu.day26.day27morning.m2dbtuils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;

/*
查询:
  ResultSetHandler
    -- BeanHandler 将查询到的第一条记录封装为对象
    -- BeanListHandler 将查询到的每一条记录封装为对象 添加到集合内
    -- ScalarHandler 获取单个值
 注意:
    1.如果属性名和字段名不一致 可以给字段起别名 保持一致
 */
public class QueryTest {

    @Test
    public void test03() throws SQLException {
        //1.创建对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        //2.准备sql
        String sql = "select count(*) from t_job";
        //3.执行操作

        Object value = qr.query(sql, new ScalarHandler<>());
        System.out.println("value = " + value);

    }

    @Test
    public void test02() throws SQLException {
     //1.创建对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        //2.准备sql
      //  String sql = "select * from t_job where jid >?";
        String sql = "SELECT jid,jname,description `desc` FROM t_job where jid > ?";
        //3.执行操作 获取结果
        List<Job> list = qr.query(sql, new BeanListHandler<>(Job.class), 2);
        //4.展示结果
        list.forEach(System.out::println);
    }

    @Test
    public void test01() throws SQLException {

        //1.创建对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        //2.准备sql
        String sql = "select * from t_job where jid = ?";
        //3.执行查询 获取结果
        Job job = qr.query(sql, new BeanHandler<>(Job.class),6);
        //4.输出结果
        System.out.println("job = " + job);

    }
}
